package org.hertsig.magiccardmarket;

import java.io.ByteArrayOutputStream;

import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ByteArrayEntity;
import org.hertsig.magiccardmarket.xml.XmlMarshaller;

@Slf4j
@RequiredArgsConstructor
public class ApiBase {
	protected final MagicCardMarketApi api;
	@Setter protected boolean printOutgoing = false;
	
	protected final <T extends HttpEntityEnclosingRequest & HttpUriRequest> HttpResponse setEntityAndExecute(T request, Object entity) {
		if (printOutgoing) {
			System.out.println("entity for " + request);
			XmlMarshaller.marshal(entity, System.out);
		}
		
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		XmlMarshaller.marshal(entity, stream);
		request.setEntity(new ByteArrayEntity(stream.toByteArray()));
		HttpResponse response = api.execute(request);
		log.debug("{} completed with response code {}", request.getMethod(), response.getStatusLine().getStatusCode());
		return response;
	}
}
